<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>人力资源管理系统 - 登录</title>
    <!-- 引入外部资源 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <!-- Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#2563eb',
                        secondary: '#64748b',
                        success: '#10b981',
                        warning: '#f59e0b',
                        danger: '#ef4444',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        };

    </script>

    <!-- 引入公共CSS -->
    <link href="css/common.css" rel="stylesheet">

    <!-- 引入API -->
    <script src="js/api.js"></script>
    <script src="js/common.js"></script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }

            .login-card {
                @apply bg-white rounded-xl shadow-lg p-8 max-w-md w-full mx-auto;
            }

            .input-field {
                @apply w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200;
            }

            .btn-login {
                @apply w-full bg-primary hover:bg-primary/90 text-white font-medium py-2 rounded-lg transition-all duration-200 flex items-center justify-center gap-2;
            }
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center p-4">
<div class="login-card">
    <div class="text-center mb-6">
        <h1 class="text-2xl font-bold text-primary mb-2">人力资源管理系统</h1>
        <p class="text-gray-500">请登录您的账户</p>
    </div>

    <form class="space-y-4" id="loginForm">
        <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="username">用户名</label>
            <div class="relative">
          <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
            <i class="fa fa-user"></i>
          </span>
                <input class="input-field pl-10" id="username" name="username" placeholder="请输入用户名" required
                       type="text">
            </div>
        </div>

        <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="password">密码</label>
            <div class="relative">
          <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
            <i class="fa fa-lock"></i>
          </span>
                <input class="input-field pl-10" id="password" name="password" placeholder="请输入密码" required
                       type="password">
            </div>
        </div>

        <div class="flex items-center justify-between">
            <div class="flex items-center">
                <input class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded" id="rememberMe" name="rememberMe"
                       type="checkbox">
                <label class="ml-2 block text-sm text-gray-700" for="rememberMe">记住我</label>
            </div>
            <div class="flex space-x-4">
                <a class="text-sm text-primary hover:text-primary/80" href="#">忘记密码?</a>
                <a class="text-sm text-primary hover:text-primary/80" href="register.html">注册</a>
            </div>
        </div>

        <div class="hidden bg-danger/10 text-danger p-3 rounded-lg text-sm" id="errorMessage"></div>

        <button class="btn-login" type="submit">
            <i class="fa fa-sign-in"></i> 登录
        </button>
    </form>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // 使用common.js中的checkAuthentication函数检查登录状态
        if (!checkAuthentication()) {
            return;
        }

        const loginForm = document.getElementById('loginForm');
        const errorMessage = document.getElementById('errorMessage');

        // 填充保存的用户名（如果有）
        const savedUsername = localStorage.getItem('savedUsername');
        if (savedUsername) {
            document.getElementById('username').value = savedUsername;
            document.getElementById('rememberMe').checked = true;
        }

        loginForm.addEventListener('submit', function (e) {
            e.preventDefault();

            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const rememberMe = document.getElementById('rememberMe').checked;

            // 显示加载状态
            showLoading();

            // 隐藏错误信息
            errorMessage.classList.add('hidden');

            // 使用全局api对象调用登录接口
            api.login({username, password})
                .then(response => {
                    // 添加检查是否包含错误消息
                    if (response.message) {
                        throw { response: { data: { message: response.message } } };
                    }
                    
                    // 保存token和用户信息
                    if (rememberMe) {
                        // 记住我：保存30天
                        setCookie('token', response.token, 30);
                        localStorage.setItem('savedUsername', username);
                    } else {
                        // 不记住：会话级存储
                        localStorage.setItem('token', response.token);
                        localStorage.removeItem('savedUsername');
                    }
// 添加调试信息
                    console.log('保存的token:', response.token);
// 构建并保存用户信息
                    const userInfo = {
                        id: response.userId || '1', // 提供默认值
                        username: response.username || username, // 使用输入的用户名作为备选
                        role: response.role
                    };
                    localStorage.setItem('userInfo', JSON.stringify(userInfo));
                    console.log('保存的userInfo:', userInfo);
                    // 登录成功提示
                    showToast('登录成功，正在跳转到首页', 'success');

                    // 延迟跳转，让用户看到提示
                    setTimeout(() => {
                        window.location.href = 'index.html';
                    }, 1500);
                })
                .catch(error => {
                    // 显示错误信息
                    errorMessage.textContent = error.response?.data?.message || '登录失败，请检查用户名和密码';
                    errorMessage.classList.remove('hidden');
                })
                .finally(() => {
                    // 隐藏加载状态
                    hideLoading();
                });
        });

        // 设置Cookie函数
        function setCookie(name, value, days) {
            let expires = '';
            if (days) {
                const date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = '; expires=' + date.toUTCString();
            }
            document.cookie = name + '=' + (value || '') + expires + '; path=/';
        }
    });
</script>
</body>
</html>